package com.whfc.wxmp.api.base.controller;

import com.whfc.common.constant.QueueConst;
import com.whfc.common.enums.AppWarnMsgChannel;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.Result;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.result.ResultUtil;
import com.whfc.entity.dto.msg.PushMsgDTO;
import com.whfc.wxmp.websocket.WebSocketSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Date;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/11/29 16:16
 */
@RestController
@RequestMapping("/mp/api/test")
public class WxWsTestController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WebSocketSessionManager sessionManager;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @PostMapping("ws/sendMsg")
    public Result wsSendMsg(@RequestParam("userId") Integer userId, @RequestParam("msg") String msg) throws IOException {
        logger.info("测试ws发送消息,userId:{},msg:{}", userId, msg);

        String user = String.valueOf(userId);
        WebSocketSession session = sessionManager.getSession(user);
        if (session == null || !session.isOpen()) {
            throw new BizException(ResultEnum.NOT_FOUND.getCode(), "用户不在线");
        }
        session.sendMessage(new TextMessage(msg));
        return ResultUtil.success();
    }

    @PostMapping("ws/sendMsg/async")
    public Result wsSendMsgsync(@RequestParam("userId") Integer userId, @RequestParam("msg") String msg) throws Exception  {
        logger.info("测试ws发送消息,userId:{},msg:{}", userId, msg);
        PushMsgDTO msgDTO = new PushMsgDTO();
        msgDTO.setId(1);
        msgDTO.setTitle("title-1");
        msgDTO.setContent("content-1");
        msgDTO.setTime(new Date());
        msgDTO.setMsgChannel(AppWarnMsgChannel.WXMP.value());
        msgDTO.setToUserId(userId);
        msgDTO.setToUserName("xx");
        amqpTemplate.convertAndSend(QueueConst.PUSH_WXMP, msgDTO);
        return ResultUtil.success();
    }
}
